package com.kmproject.haifu.mvp.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.di.component.DaggerHfMeComponent;
import com.kmproject.haifu.mvp.contract.HfMeContract;
import com.kmproject.haifu.mvp.model.entity.beans.MemberCenterUserInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.presenter.HfMePresenter;
import com.kmproject.haifu.mvp.ui.activity.FollowListActivity;
import com.kmproject.haifu.mvp.ui.activity.MemberCenterMainActivity;
import com.kmproject.haifu.mvp.ui.activity.MemberCenterUpdateLevelActivity;
import com.kmproject.haifu.mvp.ui.activity.MyCollectionActivity;
import com.kmproject.haifu.mvp.ui.activity.MyStorySelectNewActivity;
import com.kmproject.haifu.mvp.ui.activity.PersonalHomePageActivity;
import com.kmproject.haifu.mvp.ui.activity.UserLoginActivity;
import com.kmproject.haifu.mvp.ui.activity.UserSetEditInfoActivity;
import com.kmproject.haifu.mvp.ui.activity.UserSetingActivity;
import com.kmproject.haifu.mvp.ui.widget.CircleImageView;
import com.kmproject.haifu.mvp.ui.widget.MonitorDrawableEventTextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/09/2019 19:28
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class HfMeFragment extends BaseFragment<HfMePresenter> implements HfMeContract.View {
    Unbinder unbinder;
    @BindView(R.id.ll_user_info_layout)
    LinearLayout ll_user_info_layout;
    @BindView(R.id.home_me_set_img)
    ImageView homeMeSetImg;
    @BindView(R.id.home_me_header_img)
    CircleImageView homeMeHeaderImg;
    @BindView(R.id.home_me_uName_txt_new)
    MonitorDrawableEventTextView home_me_uName_txt_new;
    @BindView(R.id.home_me_ckbj_txt)
    TextView homeMeCkbjTxt;
    @BindView(R.id.home_me_wdfb_lay)
    LinearLayout homeMeWdfbLay;
    @BindView(R.id.home_me_wdsc_lay)
    LinearLayout homeMeWdscLay;
    @BindView(R.id.home_me_lljl_lay)
    LinearLayout homeMeLljlLay;
    ImageLoader glideImage;
    @BindView(R.id.hf_me_dp_num_txt)
    TextView hfMeDpNumTxt;
    @BindView(R.id.hf_me_wddp_lay)
    LinearLayout hfMeWddpLay;
    @BindView(R.id.hf_me_hyzx_lay)
    LinearLayout hfMeHyzxLay;
    @BindView(R.id.hf_me_bzfk_lay)
    LinearLayout hfMeBzfkLay;
    @BindView(R.id.hf_me_dl_img)
    ImageView hfMeDlImg;
    @BindView(R.id.home_me_gotoUpdate)
    TextView homeMeGotoUpdate;
    @BindView(R.id.home_me_wdfb_txt)
    TextView homeMeWdfbTxt;
    @BindView(R.id.home_me_wdsc_txt)
    TextView homeMeWdscTxt;
    @BindView(R.id.home_me_wdgz_txt)
    TextView homeMeWdgzTxt;
    @BindView(R.id.home_me_wdgz_lay)
    LinearLayout homeMeWdgzLay;
    @BindView(R.id.home_me_lljl_txt)
    TextView homeMeLljlTxt;
    @BindView(R.id.hf_me_wddp_line)
    View hfMeWddpLine;

    MemberCenterUserInfoBean mmemberCenterUserInfoBean;
    @BindView(R.id.hf_me_wddp_txt)
    TextView hfMeWddpTxt;


    public static HfMeFragment newInstance() {
        HfMeFragment fragment = new HfMeFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerHfMeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_hf_me, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        hfMeWddpLine.setVisibility(View.GONE);
        hfMeWddpLay.setVisibility(View.GONE);
        if (glideImage == null) {
            glideImage = ArmsUtils.obtainAppComponentFromContext(getActivity()).imageLoader();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (AppUtil.userIsLogin(getActivity())) {
            homeMeGotoUpdate.setVisibility(View.VISIBLE);
//            hfMeEditImg.setVisibility(View.VISIBLE);
            setRightDrawable(true);
            homeMeCkbjTxt.setVisibility(View.GONE);
            hfMeDlImg.setVisibility(View.VISIBLE);
            homeMeWdfbTxt.setText("");
            homeMeWdscTxt.setText("");
            homeMeWdgzTxt.setText("");//关注
            homeMeLljlTxt.setText("");
            hfMeDpNumTxt.setText("");
            //用户已经登录
            UserBean userBean = DataHelper.getDeviceData(getActivity(), AppConstant.USER_INFO);//获取用户信息
            if (userBean != null) {
                if (userBean.getAvatar() != null && !TextUtils.isEmpty(userBean.getAvatar())) {
                    glideImage.loadImage(getActivity(), ImageConfigImpl.builder().url(userBean.getAvatar()).imageRadius(5)
                            .imageView(homeMeHeaderImg)
                            .build());
                } else {
                    homeMeHeaderImg.setImageResource(R.drawable.default_headimage);
                }
                home_me_uName_txt_new.setText((userBean.getNickName() == null || TextUtils.isEmpty(userBean.getNickName())) ? "您还没设置昵称" : userBean.getNickName());
                homeMeCkbjTxt.setText(ArmsUtils.getString(getActivity(), R.string.home_me_ckbj));
            } else {
                homeMeHeaderImg.setImageResource(R.drawable.default_headimage);
            }
            mPresenter.getMemberLevelByUser();
//            home_me_uName_txt_new.setOnDrawableClickListener(new MonitorDrawableEventTextView.OnDrawableClickListener() {
//                @Override
//                public void onEndClick() {
//                    ArmsUtils.startActivity(UserSetEditInfoActivity.class);
//                }
//
//                @Override
//                public void onStartClick() {
//
//                }
//            });
//            home_me_uName_txt_new.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    UserBean userBean = DataHelper.getDeviceData(getActivity(), AppConstant.USER_INFO);
////                    Intent intent = new Intent(getActivity(), PersonalHomePageActivity.class);
////                    intent.putExtra("userId", userBean.getUserId());
//
//                    Intent intent = new Intent(getActivity(), UserLoginActivity.class);
//                    intent.putExtra("userId", userBean.getUserId());
//                    ArmsUtils.startActivity(intent);
//                }
//            });
        } else {
            homeMeWdfbTxt.setText("0");
            homeMeWdscTxt.setText("0");
            homeMeWdgzTxt.setText("0");//关注
            homeMeLljlTxt.setText("0");
            hfMeDpNumTxt.setText("0个店铺");
            hfMeWddpLine.setVisibility(View.GONE);
            hfMeWddpLay.setVisibility(View.GONE);
            homeMeGotoUpdate.setVisibility(View.GONE);
//            hfMeEditImg.setVisibility(View.GONE);
            setRightDrawable(false);
            homeMeCkbjTxt.setVisibility(View.VISIBLE);
            hfMeDlImg.setVisibility(View.GONE);
            home_me_uName_txt_new.setText(ArmsUtils.getString(getActivity(), R.string.home_me_wdl));
            homeMeCkbjTxt.setText(ArmsUtils.getString(getActivity(), R.string.home_me_dlhckbj));
            homeMeHeaderImg.setImageResource(R.drawable.default_headimage);
        }
    }

    /**
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.home_me_wdgz_lay, R.id.home_me_gotoUpdate, R.id.hf_me_wddp_lay, R.id.hf_me_hyzx_lay, R.id.hf_me_bzfk_lay, R.id.home_me_set_img, R.id.home_me_header_img,
            R.id.home_me_uName_txt_new, R.id.home_me_ckbj_txt, R.id.home_me_wdfb_lay, R.id.home_me_wdsc_lay, R.id.home_me_lljl_lay})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
//            case R.id.hf_me_edit_img:
//                ArmsUtils.startActivity(UserSetEditInfoActivity.class);
//                break;
            case R.id.home_me_set_img:
                if (AppUtil.userIsLogin(getActivity())) {
                    ArmsUtils.startActivity(UserSetingActivity.class);
                } else {
                    ArmsUtils.startActivity(UserLoginActivity.class);
                    ArmsUtils.makeText(getActivity(), "请先登录");
                }
                break;
            case R.id.home_me_header_img:
            case R.id.home_me_uName_txt_new:
                goToPersonalHomePage();
                break;
            case R.id.home_me_ckbj_txt:
                if (AppUtil.userIsLogin(getActivity())) {
                    ArmsUtils.startActivity(UserSetingActivity.class);
                } else {
                    ArmsUtils.makeText(getActivity(), "请先登录");
                }
                break;
            case R.id.home_me_wdfb_lay:
                if (AppUtil.userIsLogin(getActivity())) {
                    intent = new Intent(getActivity(), MyCollectionActivity.class);
                    intent.putExtra("type", 0);
                    intent.putExtra("selectIndex", 0);
                    ArmsUtils.startActivity(intent);
                } else {
                    ArmsUtils.makeText(getActivity(), "请先登录");
                }
                break;
            case R.id.home_me_wdsc_lay:
                if (AppUtil.userIsLogin(getActivity())) {
                    intent = new Intent(getActivity(), MyCollectionActivity.class);
                    intent.putExtra("selectIndex", 1);
                    intent.putExtra("type", 1);
                    ArmsUtils.startActivity(intent);
                } else {
                    ArmsUtils.makeText(getActivity(), "请先登录");
                }
                break;
            case R.id.home_me_lljl_lay:
                if (AppUtil.userIsLogin(getActivity())) {
                    UserBean userBean = DataHelper.getDeviceData(getContext(), AppConstant.USER_INFO);//获取用户信息
                    intent = new Intent(getActivity(), FollowListActivity.class);
                    assert userBean != null;
                    intent.putExtra("userId", userBean.getUserId());
                    ArmsUtils.startActivity(intent);
                } else {
                    ArmsUtils.makeText(getActivity(), "请先登录");
                }
                break;
            case R.id.hf_me_wddp_lay:
                if (!AppUtil.userIsLogin(getActivity())) {
                    ArmsUtils.startActivity(UserLoginActivity.class);
                    ArmsUtils.makeText(getActivity(), "请先登录");
                    return;
                }

                Intent intentStory = new Intent(getActivity(), MyStorySelectNewActivity.class);
                intentStory.putExtra("MemberCenterUserInfoBean", mmemberCenterUserInfoBean);
                ArmsUtils.startActivity(intentStory);
                break;
            case R.id.hf_me_hyzx_lay:
                if (!AppUtil.userIsLogin(getActivity())) {
                    ArmsUtils.startActivity(UserLoginActivity.class);
                    ArmsUtils.makeText(getActivity(), "请先登录");
                    return;
                }
                ArmsUtils.startActivityForResult(new Intent(getActivity(), MemberCenterMainActivity.class), 1001);
                break;
            case R.id.hf_me_bzfk_lay:
                 AppUtil.gotoMessage(getActivity());
                break;

            case R.id.home_me_gotoUpdate:
                if (!AppUtil.userIsLogin(getActivity())) {
                    ArmsUtils.startActivity(UserLoginActivity.class);
                    ArmsUtils.makeText(getActivity(), "请先登录");
                    return;
                }
                if (mmemberCenterUserInfoBean == null) {
                    return;
                }
                Intent intent1 = new Intent(getActivity(), MemberCenterUpdateLevelActivity.class);
                intent1.putExtra("MemberCenterUserInfoBean", mmemberCenterUserInfoBean);
                ArmsUtils.startActivityForResult(intent1, 1001);
                break;
            case R.id.home_me_wdgz_lay:
                if (AppUtil.userIsLogin(getActivity())) {
                    intent = new Intent(getActivity(), MyCollectionActivity.class);
                    intent.putExtra("selectIndex", 2);
                    intent.putExtra("type", 2);
                    ArmsUtils.startActivity(intent);
                } else {
                    ArmsUtils.makeText(getActivity(), "请先登录");
                }
                break;
        }
    }

    private void goToPersonalHomePage() {
        if (AppUtil.userIsLogin(getActivity())) {
            UserBean ub = DataHelper.getDeviceData(getContext(), AppConstant.USER_INFO);
            Intent intent = new Intent(getContext(), PersonalHomePageActivity.class);
            assert ub != null;
            intent.putExtra("userId", String.valueOf(ub.getUserId()));
            ArmsUtils.startActivity(intent);
        } else {
            ArmsUtils.startActivity(UserLoginActivity.class);
            ArmsUtils.makeText(getActivity(), "请先登录");
        }
    }

    @Override
    public void getMemberLevelByUserSuccess(MemberCenterUserInfoBean memberCenterUserInfoBean) {
        if (memberCenterUserInfoBean == null) {
            return;
        }
        DataHelper.saveDeviceData(getActivity(), AppConstant.user_memberInfo, memberCenterUserInfoBean);
        if (AppUtil.isDialogShow && (memberCenterUserInfoBean.getStoreTotal() == -1 || memberCenterUserInfoBean.getStoreTotal() > 0)) {
            //入口：有店铺用户开通会员后，如果开通会员等级店铺数量<已有店铺数量时，跳转到此页面选择开启哪1个或哪几个店铺：
            if (memberCenterUserInfoBean.getStoreTotal() != -1 && memberCenterUserInfoBean.getStoreTotal() < memberCenterUserInfoBean.getIsShowStoreCount() && memberCenterUserInfoBean.getCanShowStoreCount() > 0) {
                //跳转到开启店铺界面
                Intent intentStory = new Intent(getActivity(), MyStorySelectNewActivity.class);
                intentStory.putExtra("MemberCenterUserInfoBean", mmemberCenterUserInfoBean);
                intentStory.putExtra("selectModel", 1);
                ArmsUtils.startActivity(intentStory);
                return;
            }


            //新升级以后，并且店铺数大一1
            //弹框提示
            AppUtil.isDialogShow = false;//置回标志位
            new AlertView("提示", "您已成功开通" + memberCenterUserInfoBean.getMemberLevel().getLevelName() + "，可以新增" + (memberCenterUserInfoBean.getStoreTotal() == -1 ? "无限" : memberCenterUserInfoBean.getStoreTotal()) + "个店铺，可在“我的-我的店铺”新增或管理", "知道了", new String[]{"立即新增店铺"}, null, getActivity(), AlertView.Style.Alert, new AlertViewOnItemClickListener() {

                @Override
                public void onItemClick(Object o, int position) {
                    if (position == AlertView.CANCELPOSITION) {
                        //点击取消按钮

                    }else {
                       Intent intent=new Intent(getActivity(),MyStorySelectNewActivity.class);
                        intent.putExtra("gotoAddStore",true);
                        getActivity().startActivity(intent);
                    }
                }
            }).show();
        }


        if (memberCenterUserInfoBean.getMemberLevel().getLevelType() == 0) {
            //最小等级
            homeMeGotoUpdate.setText(ArmsUtils.getString(getActivity(), R.string.hf_me_qsj));
        } else {
            //大于最小等级
            homeMeGotoUpdate.setText(ArmsUtils.getString(getActivity(), R.string.hf_me_qxf));
        }
        mmemberCenterUserInfoBean = memberCenterUserInfoBean;
        if (memberCenterUserInfoBean.getStoreTotal() == -1 || memberCenterUserInfoBean.getStoreCount() > 0 || memberCenterUserInfoBean.getStoreTotal() > 0) {
            hfMeWddpLine.setVisibility(View.VISIBLE);
            hfMeWddpLay.setVisibility(View.VISIBLE);
//            if (memberCenterUserInfoBean.getMemberLevel().getLevelType() == 0 && memberCenterUserInfoBean.getStoreCount() > 0) {
//                //设置灰色不可点击
//                hfMeDpNumTxt.setTextColor(ArmsUtils.getColor(getActivity(), R.color.color_999999));
//                hfMeWddpTxt.setTextColor(ArmsUtils.getColor(getActivity(), R.color.color_999999));
//                hfMeWddpLay.setEnabled(false);
//            }
        } else {
            hfMeWddpLine.setVisibility(View.GONE);
            hfMeWddpLay.setVisibility(View.GONE);
        }
        glideImage.loadImage(getActivity(), ImageConfigImpl.builder().url(memberCenterUserInfoBean.getMemberLevel().getHeadImage()).imageRadius(5)
                .imageView(hfMeDlImg)
                .build());
        homeMeWdfbTxt.setText(memberCenterUserInfoBean.getPublishCount() + "");
        homeMeWdscTxt.setText(memberCenterUserInfoBean.getSeekingCount() + "");
        homeMeWdgzTxt.setText(memberCenterUserInfoBean.getCollectionCount() + "");//关注
        homeMeLljlTxt.setText(memberCenterUserInfoBean.getAttentionCount() + "");
        hfMeDpNumTxt.setText(memberCenterUserInfoBean.getStoreCount() + "个店铺");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1001 && resultCode == Activity.RESULT_OK && data != null) {
            if (data.hasExtra("isDialogShow") && data.getBooleanExtra("isDialogShow", false)) {
                AppUtil.isDialogShow = true;

            }

        }
    }

    /**
     * 控制右边的编辑图标显示
     *
     * @param isShowRight
     */
    public void setRightDrawable(boolean isShowRight) {
        Drawable leftDrawable = getResources().getDrawable(R.drawable.hf_me_edit_icon);
        leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(),
                leftDrawable.getMinimumHeight());
//        if (isShowRight) {
//            home_me_uName_txt_new.setCompoundDrawables(null, null, leftDrawable, null);
//        } else {
//            home_me_uName_txt_new.setCompoundDrawables(null, null, null, null);
//        }


    }

    @Override
    public void onPause() {
        super.onPause();
        AppUtil.isDialogShow = false;
    }
}
